//
//  ChartContent.swift
//  HealthMonitoring
//
//  Created by 珠海正杰 on 2018/7/9.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

/**
 \ 图表内容， 属于HealthLog 部分内容
 */

import UIKit
import LTScrollView
import MJRefresh
import SwiftyJSON

class ChartContent: HMViewController, LTTableViewProtocal{

    var adjustValue: CGFloat = 0.0
    var _title: String? = ""
    var btn1 = UIButton()  //日
    var btn2 = UIButton()  //月
    var btn3 = UIButton()  // 年
    public var urlId: String? = ""
    public var chartUrl: String? = ""
    public var averageUrl: String? = ""
    var dataJson = JSON()      //数据
    var chartDataJson = JSON()    // 折线图数据
    var averageDataJson = JSON()  //平均数据
    var cc_healthLog:HealthLog?
    
    
    
    
    public lazy var CCTableView : UITableView = {
//        let H: CGFloat = glt_iphoneX ? (self.view.wHeight - 44.0 - 64 - 24 - 34 - adjustValue) : self.view.wHeight - 44 - 64 - adjustValue
        let H: CGFloat = self.view.wHeight - 44.0 - 64.0 - adjustValue
        let tableView = tableViewConfig(CGRect(x: 0, y: 44, width: view.bounds.width, height: H), self, self, nil)
        return tableView
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        view.addSubview(CCTableView)
        glt_scrollView = CCTableView
        reftreshData()
        if #available(iOS 11.0, *) {
            glt_scrollView?.contentInsetAdjustmentBehavior = .never
        }else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        
        self.CCTableView.register(ChartViewCell.classForCoder(), forCellReuseIdentifier: "ChartViewCell")
        self.CCTableView.register(ChartInputDataCell.classForCoder(), forCellReuseIdentifier: "ChartInputDataCell")
        
    }   // 备注， ChartContent ( Load -> Appear)  第一次加载
        // Load -> Appear -> 选项卡切换事件
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 表示初始化一次？
        UserDefaults.standard.set(self.urlId!, forKey: self.urlId!)
        
        let d  = Date()
        let startStr = "\(d.year)-\(d.month)-\(d.day) 00:00:00";
        let endStr = "\(d.year)-\(d.month)-\(d.day) 23:00:00";
        self.requestData(startDateStr: startStr, endDateStr: endStr)
    }
    

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated) //离开
        print("viewWillDisappear----------------YTYanK----WillDisappear")  //返回来到了这里
        
        //         UserDefaults.standard.set(self.ulrIds[index], forKey: configure.shareConfigure.HEALTH_SELECT_INDEX)
        //        UserDefaults.standard.remove
        
    }

    /// 请求数据
    func requestData( startDateStr: String, endDateStr: String) {
        let startDate = Date.getFromDate(dateString: startDateStr)
        let endDate =   Date.getFromDate(dateString:  endDateStr)
        
        let startInt = ((startDate?.timeIntervalSince1970)! * 1000)
        let endInt = ((endDate?.timeIntervalSince1970)! * 1000)
        
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "user/data/" + self.urlId!, parameters: ["st": startInt, "et": endInt, "page": 0, "perPage": 100], success: { (json) in
            
            self.dataJson = json["data"]["list"];
            self.chartDataJson = json["data"]["list"];
            
            self.CCTableView.reloadData()
//            self.CCTableView.reloadSections([1], with: UITableViewRowAnimation.left)
//            self.CCTableView.reloadSections([0], with: UITableViewRowAnimation.none)
            
        }, fail: { (code, err) in
            // print("---->>>", code, err);
        }) {
            
        }
        
    

    }
    
    
}  
extension ChartContent {
    //  私人文件
    fileprivate func reftreshData() {
        self.CCTableView.mj_footer = MJRefreshBackNormalFooter {[weak self] in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
                print("上拉加载更多数据")
                self?.CCTableView.mj_footer.endRefreshing()
            })
        }
    }
}

extension ChartContent: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section != 0 {
            return 0
        }
        return 44
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section != 0 {
            return dataJson.count
        }else {
            return  1
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section != 0 {
             let cell = tableView.dequeueReusableCell(withIdentifier: "ChartInputDataCell") as! ChartInputDataCell
            cell.setJson(json: ["data": dataJson[indexPath.row], "urlId": self.urlId!])
            cell.editBlock = {
                (btn, data) -> () in
                
                var jsonData : JSON?
                var urlStr = ""  //删除、修改 的url
                var keyAry = Array<String>()
                if self.urlId == "blood-pressure-all"  {
                  jsonData = JSON.init(arrayLiteral: ["label":"收缩压", "value":data["systolicPressure"].stringValue],["label":"舒张压", "value":data["diastolicPressure"].stringValue],["label":"心率", "value":data["heartRate"].stringValue])
                    
                    // -
                    urlStr = "user/data/blood-pressure"
                    keyAry = ["systolicPressure", "diastolicPressure", "heartRate"]
                    
                }else if self.urlId == "weight-all" {
                    let type =  data["type"].intValue
                    jsonData = JSON.init(arrayLiteral: ["label":"体重", "value":data["weight"].stringValue],["Button":["餐前", "餐后"], "selected": type])
                    
                    urlStr = "user/data/weight"
                    keyAry = ["weight","type"]
                    
                }else if self.urlId == "body-temp-all" {
                    jsonData = JSON.init(arrayLiteral: ["label":"体温", "value":data["temp"].stringValue])
                    
                    urlStr = "user/data/body-temp"
                    keyAry = ["temp"]
                    
                }else if self.urlId == "heart-rate-all" {

                    let type =  data["type"].intValue
                        jsonData = JSON.init(arrayLiteral: ["label":"心率", "value":data["heartRate"].stringValue],["Button":["运动", "静息"], "selected": type])
                    
                    urlStr = "user/data/heart-rate"
                    keyAry = ["type", "heartRate"]
                    
                }else if self.urlId == "blood-glucose-all" {
                    jsonData = JSON.init(arrayLiteral: ["label":"血糖", "value":data["bloodGlucose"].stringValue])
                    
                    urlStr = "user/data/blood-glucose"
                    keyAry = ["bloodGlucose"]
                }

                let editView  = HMEditView.init(id: self.urlId!, frame: CGRect.zero, data: jsonData!)   //init(frame: )
                self.cc_healthLog?.view.addSubview(editView)
                editView.hiddenView = {
                    (subut) ->() in
                     editView.removeFromSuperview()
                    print("--->>",editView)
                }
                
                // 保存
                editView.saveData = {
                    (save) ->() in
                    var savePar = Dictionary<String, Any>()
                    var dic =  self.dataJson[indexPath.row].dictionaryValue
                    let time = dic["recordTime"]!.stringValue
                  
                    
                   let strInt = Date.stringToTimeStamp(stringTime: String.chineseTime(frome: time))

                    var i = 0
                
                    for key in keyAry {
                        savePar[key] = save[i].stringValue
                        self.dataJson[indexPath.row][key] = save[i]
                        self.chartDataJson[indexPath.row][key] = save[i]
                        i += 1
                    }

                    savePar["id"] = dic["id"]!.stringValue
                    savePar["recordTime"] = "\(Int(strInt)!  * 1000)"
                    
                    NetRequestTool.shareInstance.met = .post
                    NetRequestTool.requestForJSON(url: urlStr, parameters: savePar, success: { (json) in
                        if json["code"].intValue == 0 {
                            savePar.removeAll()
                            
                            self.CCTableView.reloadData()
                        }
                    }, fail: { (code, err) in
                        print("\n =>>", code, err)
                    }) {
                        
                        
                        
                    }
                    
                }
                
                // 删除
                editView.removeData = {
                    (removeData) -> () in
                       var remPar = Dictionary<String, Any>()
                       let dic =  self.dataJson[indexPath.row].dictionaryValue
                       remPar["id"] = dic["id"]!.stringValue

                
                      var   ary =  self.dataJson.arrayValue
                       ary.remove(at: indexPath.row)

                    NetRequestTool.shareInstance.met = .delete
                    NetRequestTool.request(url: urlStr, parameters: remPar, success: { (json) in
                        if json["code"].intValue == 0 {
                            remPar.removeAll()
                            self.dataJson = JSON.init(ary)
                            self.chartDataJson = JSON.init(ary)
                            self.CCTableView.reloadData()

                        }
                    }, fail: { (code, err) in
                        print("\n =>>", code, err)
                    }, complete: {

                    })

                }
                
            }

            return cell
        }else  {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ChartViewCell") as! ChartViewCell
            cell.setJson(json: ["data": chartDataJson, "chartUrl": chartUrl!, "average": averageDataJson])
             return cell
        }
       
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("点击了第\(indexPath.row + 1)行")
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     
        if indexPath.section != 0 {
            return 80.0
        }else {
            return 350.0
        }
    }

    /// 头部 日月年
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        if section != 0 {
            return nil
        }else {
            let view = UIView.init(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 40))
            view.backgroundColor = UIColor.white
            
            view.addSubview(btn1)
            view.addSubview(btn2)
            view.addSubview(btn3)
            btn1.tag = 110
            btn2.tag = 120
            btn3.tag = 130
            btn1.isSelected = true
            btn2.isSelected = false
            btn3.isSelected = false
            btn1.setTitle("日", for: UIControlState.normal)
            btn2.setTitle("月", for: UIControlState.normal)
            btn3.setTitle("年", for: UIControlState.normal)
            btn1.setTitleColor(UIColor.white, for: .selected)
            btn1.setTitleColor(UIColor.black, for: .normal)
            btn1.backgroundColor = configure.shareConfigure.HMColor1
            btn1.layer.cornerRadius = 8
            btn1.layer.borderWidth = 1
            btn1.layer.borderColor = configure.shareConfigure.HMColor1.cgColor
            btn2.layer.borderWidth = 1
            btn3.layer.borderWidth = 1
            btn2.setTitleColor(.black, for: .normal)
            btn2.setTitleColor(.white, for: .selected)
            btn3.setTitleColor(.black, for: .normal)
            btn3.setTitleColor(.white, for: .selected)
            btn2.backgroundColor = UIColor.white
            btn3.backgroundColor = UIColor.white
        
            btn2.layer.cornerRadius = btn1.layer.cornerRadius
            btn3.layer.cornerRadius = btn1.layer.cornerRadius
            
            btn1.addTarget(self, action: #selector(selectorData), for: UIControlEvents.touchUpInside)
            btn2.addTarget(self, action: #selector(selectorData), for: UIControlEvents.touchUpInside)
            btn3.addTarget(self, action: #selector(selectorData), for: UIControlEvents.touchUpInside)
            
            
            btn2.centerXYAlign(view: view)
            btn2.widthConstrain(predicate: "80")
            btn2.heightConstrain(predicate: "30")
            
            btn1.trailingHorizontally(view: btn2)
            btn1.centerYAlign(view: btn2)
            btn1.widthConstrain(predicate: "80")
            btn1.heightConstrain(predicate: "30")
            
            btn3.leadingHorizontally(view: btn2)
            btn3.centerYAlign(view: btn2)
            btn3.widthConstrain(predicate: "80")
            btn3.heightConstrain(predicate: "30")
            
            return view

        }
        
    }
    
    @objc func selectorData(sender: UIButton) {
        print("----->", sender.tag)

        HMPickerView.creatorDate()
        if sender.tag == 110 { // 年、月、日
            HMPickerView.sharePicker.setDateRange(max: [0,0,0], min: [-1,0,0])
        }else if sender.tag == 120 {
            HMPickerView.sharePicker.setDateRange(max: [0,0,0], min: [-1,0,0])
        }else if sender.tag == 130 {
            HMPickerView.sharePicker.setDateRange(max: [0,0,0], min: [-1,0,0])
        }
        HMPickerView.sharePicker.sign = "\(sender.tag)"
        HMPickerView.sharePicker.returnDatePicker = {
            (picker) ->() in
            
            
            let formatter = DateFormatter()
            //日期样式
            formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            print(formatter.string(from: picker.date))

            if sender.tag == 110 {
                 self.btn1.backgroundColor = configure.shareConfigure.HMColor1
                 self.btn2.backgroundColor = UIColor.white
                 self.btn3.backgroundColor = UIColor.white
                 self.btn1.layer.borderColor = configure.shareConfigure.HMColor1.cgColor
                 self.btn2.layer.borderColor = UIColor.black.cgColor
                 self.btn3.layer.borderColor  = UIColor.black.cgColor
                self.btn1.isSelected = true
                self.btn2.isSelected = false
                self.btn3.isSelected = false
            }else if sender.tag == 120 {
                self.btn1.backgroundColor = UIColor.white
                self.btn2.backgroundColor = configure.shareConfigure.HMColor1
                self.btn3.backgroundColor = UIColor.white
                self.btn1.layer.borderColor = UIColor.black.cgColor
                self.btn2.layer.borderColor = configure.shareConfigure.HMColor1.cgColor
                self.btn3.layer.borderColor  = UIColor.black.cgColor
                self.btn1.isSelected = false
                self.btn2.isSelected = true
                self.btn3.isSelected = false
                
            }else if sender.tag == 130 {
                self.btn1.backgroundColor = UIColor.white
                self.btn2.backgroundColor = UIColor.white
                self.btn3.backgroundColor = configure.shareConfigure.HMColor1
                
                self.btn1.layer.borderColor = UIColor.black.cgColor
                self.btn2.layer.borderColor = UIColor.black.cgColor
                self.btn3.layer.borderColor  = configure.shareConfigure.HMColor1.cgColor
                
                self.btn1.isSelected = false
                self.btn2.isSelected = false
                self.btn3.isSelected = true
            }
            
            
            let startStr = formatter.string(from: picker.date)  //"\(d.year)-\(d.month)-\(d.day) 00:00:00";
            let endStr = startStr.substring(toIndex: 11) + "23:59:59"
            self.requestData(startDateStr: startStr, endDateStr: endStr)
            
            
        }

    }
}
